<template>
	<view class="container">
		<!-- 顶部标题栏 -->
		<view class="header">
			<view class="header-title">设备管理</view>
			<uni-fab :pattern="pattern" horizontal="right" @fabClick="openDialog"></uni-fab>
		</view>

		<!-- 筛选区域 -->
		<view class="filter-bar">
			<!-- 使用 uni-data-select 美观的下拉框 -->
			<view class="picker-group">
				<uni-data-select v-model="areaSelected" :localdata="areaOptions" placeholder="请选择区域" />
			</view>
		</view>

		<!-- ATM设备列表 -->
		<view v-if="loading" class="loading">加载中...</view>
		<view v-else-if="filteredList.length === 0" class="no-data">暂无设备，请检查筛选条件</view>
		<view v-else>
			<view v-for="atm in filteredList" :key="atm.id" class="atm-card" @click="goToDetail(atm)">
				<view class="card-header">
					<text class="atm-title">{{ atm.code }}</text>
					<text class="status" :class="atm.status === 'on' ? 'online' : 'offline'">
						{{ atm.status === 'on' ? '🟢 运行中' : '🔴 已关机' }}
					</text>
				</view>
				<view class="card-body">
					<view class="left">
						<image class="atm-image" :src="atm.image" mode="aspectFill" @click="goToDetail(atm)" />
						<view class="card-info">
							<text>区域：{{ atm.areaName }}</text>
							<text>库存金额：￥{{ atm.stock }}</text>
						</view>
					</view>
					<view class="right">
						<button class="detail-btn" @click="goToDetail(atm)">详细信息</button>
					</view>
				</view>

			</view>
		</view>

		<uni-popup ref="addPopup" type="bottom" background-color="transparent">
			<view class="dialog-overlay" @click.self="closeDialog" @touchmove.stop.prevent>
				<view class="dialog" role="dialog" aria-modal="true" aria-labelledby="dialogTitle">
					<header class="dialog-header">
						<text id="dialogTitle">添加ATM设备</text>
						<button @click="closeDialog" class="close-btn" aria-label="关闭弹窗">✕</button>
					</header>

					<form @submit.prevent="submitAddition" class="dialog-body">
						<div class="form-group">
							<label>添加时间</label>
							<picker mode="date" disabled>
								<view class="input-field">{{ addInfo.applyTime }}</view>
							</picker>
						</div>

						<div class="form-group">
							<label>您的工号<span class="required">*</span></label>
							<input type="text" v-model.trim="addInfo.yourAccount" required class="input-field" />
						</div>

						<div class="form-group">
							<label>设备编号<span class="required">*</span></label>
							<input placeholder="10位编号，如ATM#abc123" type="text" v-model.trim="addInfo.atmCode" required
								class="input-field" />
						</div>

						<div class="form-group">
							<label>设备所属区域<span class="required">*</span></label>
							<picker :range="areaOptions" range-key="text" @change="onAreaChange">
								<view class="input-field">
									{{ addInfo.newArea || '请选择分配区域' }}
								</view>
							</picker>
						</div>

						<div class="form-group">
							<label>设备详细地址</label>
							<textarea placeholder="可选，推荐填写。" v-model.trim="addInfo.position" required
								class="input-field" />
						</div>

						<footer class="dialog-footer">
							<button type="button" @click="closeDialog" class="cancel-btn">取消</button>
							<button type="button" @click="submitAddition" class="submit-btn">确认添加</button>
						</footer>
					</form>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		getAtms,
	} from '@/api/atm';
	import {
		getAreas,
		getAreaById
	} from '@/api/area';
	import {
		getManagersByAreaId
	} from '@/api/user';
	import formatDateTime from '@/utils/formatDateTime';

	export default {
		data() {
			return {
				// 下拉框数据格式必须为 { value, text }
				areaOptions: [{
					value: null,
					text: ''
				}],
				areaSelected: '',
				devices: [],
				loading: false,
				activeButton: null,
				pattern: {
					buttonColor: "#BD3124"
				},
				addInfo: {
					applyTime: '',
					atmCode: '',
					newArea: '',
					newAreaId: null,
					position: '',
					yourAccount: '',
				},
				maxDate: '',
			}
		},

		computed: {
			filteredList() {
				return this.devices.filter(item => {
					return !this.areaSelected || item.areaId === this.areaSelected;
				})
			}
		},

		onLoad: async function() {
			await this.fetchData();
		},

		methods: {
			async fetchData() {
				this.loading = true;
				const areaList = await getAreas();
				// console.log(areaList);
				uni.setStorageSync('areaDatas', areaList);
				this.areaOptions = areaList.map(area => ({
					value: area.id,
					text: area.name,
					tip: area.district
				}));

				const result = await getAtms();
				if (result.code === 200) {
					const deviceList = result.data;
					this.devices = deviceList.map(d => ({
						id: d.id,
						code: d.atmCode,
						status: d.status,
						stock: d.money,
						areaId: d.areaId,
						areaName: this.getAreaNameById(d.areaId),
						image: '/static/ATM_pic.png',
						manager: '张三',
					}));
					this.loading = false;
				}
			},

			goToDetail(atm) {
				uni.navigateTo({
					url: `/pages/deviceManagement/deviceDetails?id=${atm.id}`
				})
			},

			getAreaNameById(areaId) {
				const areaList = uni.getStorageSync('areaDatas');
				let result;
				areaList.forEach(area => {
					if (result) return;
					if (area.id === areaId) {
						result = area.name;
					}
				});
				return result;
			},

			openDialog() {
				const now = formatDateTime(new Date());
				this.addInfo = {
					applyTime: now,
					atmCode: '',
					newArea: '',
					newAreaId: null,
					position: '',
					yourAccount: '',
				};
				this.$refs.addPopup.open();
			},

			closeDialog() {
				this.$refs.addPopup.close();
			},

			onAreaChange(e) {
				this.addInfo.newArea =
					`澳门 ${this.areaOptions[e.detail.value].tip} ${this.areaOptions[e.detail.value].text}`;
				this.addInfo.newAreaId = this.areaOptions[e.detail.value].value;
			},

			submitAddition() {
				const info = this.addInfo;

				if (!info.yourAccount.trim()) {
					uni.showToast({
						title: '请输入工号',
						icon: 'none',
						duration: 1500
					});
					return;
				}
				if (!info.atmCode.trim()) {
					uni.showToast({
						title: '请输入设备编号',
						icon: 'none',
						duration: 1500
					});
					return;
				}
				if (!info.newAreaId) {
					uni.showToast({
						title: '请选择分配区域',
						icon: 'none',
						duration: 1500
					});
					return;
				}
				if (!/ATM#[a-z]{3}\d{3}/.test(info.atmCode)) {
					uni.showToast({
						title: '请输入有效的设备编号',
						icon: 'none',
						duration: 1500
					});
					return;
				}


				const data = {
					atmCode: this.addInfo.atmCode,
					areaId: this.addInfo.newAreaId,
					position: this.addInfo.position ? this.addInfo.position : this.addInfo.newArea
				}
				console.log(data);
			}
		}
	}
</script>

<style scoped>
	.container {
		background-color: #f8f8f8;
		min-height: 100vh;
	}

	.header {
		background-color: #BD3124;
		padding: 0 30rpx 20rpx;
		color: #fff;
		font-size: 36rpx;
		font-weight: bold;
		text-align: center;
	}

	.filter-bar {
		background-color: #fff;
		margin: 20rpx;
		padding: 24rpx;
		border-radius: 20rpx;
		/* box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05); */
	}

	.picker-group {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
		margin-bottom: 30rpx;
	}

	.button-bar {
		display: flex;
		justify-content: space-around;
	}

	.btn {
		flex: 1;
		margin: 0 10rpx;
		padding: 20rpx;
		font-size: 26rpx;
		border-radius: 12rpx;
		background-color: #eee;
		color: #333;
		text-align: center;
	}

	.btn.active {
		background-color: #BD3124;
		color: #fff;
	}

	.loading,
	.no-data {
		padding: 60rpx;
		text-align: center;
		color: #999;
		font-size: 28rpx;
	}

	.atm-card {
		background: #fff;
		margin: 20rpx;
		border-radius: 16rpx;
		padding: 24rpx;
		/* box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05); */
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		font-size: 28rpx;
		font-weight: 600;
	}

	.online {
		color: #28a745;
	}

	.offline {
		color: #dc3545;
	}

	.card-body {
		display: flex;
		justify-content: space-between;
		align-items: flex-end;
	}

	.atm-image {
		width: 120px;
		height: 120px;
		margin: 20rpx 0;
		border-radius: 12rpx;
		object-fit: contain;
	}

	.card-info text {
		display: block;
		font-size: 26rpx;
		margin-bottom: 6rpx;
		color: #333;
	}

	.card-body .right {
		display: flex;
		justify-content: flex-end;
	}

	.detail-btn {
		margin-top: 20rpx;
		margin-right: 0;
		width: 80px;
		height: 28px;
		line-height: 27px;
		background-color: #FFF;
		text-align: center;
		border-radius: 8px;
		font-size: 12px;
		color: #D20000;
		border: 0.5px solid #D20000;
	}

	.detail-btn::after {
		display: none;
	}

	/* 弹窗样式 */
	.dialog-overlay {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.35);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 9999;
		backdrop-filter: blur(4px);
	}

	.dialog {
		background-color: #fff;
		width: 100%;
		max-width: 360px;
		border-radius: 16px;
		box-shadow: 0 12px 24px rgba(0, 0, 0, 0.2);
		display: flex;
		flex-direction: column;
		overflow: hidden;
		animation: fadeInScale 0.5s ease forwards;
	}

	@keyframes fadeInScale {
		0% {
			opacity: 0;
			transform: scale(0.95);
			transform: rotate(0deg);
		}

		50% {
			opacity: 0;
			transform: scale(2);
			transform: rotate(360deg);
		}

		100% {
			opacity: 1;
			transform: scale(1);
			transform: rotate(0deg);
		}
	}

	.dialog-header {
		padding: 18px 22px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-weight: 700;
		font-size: 20px;
		color: #BD3124;
		border-bottom: 1px solid #eee;
	}

	.close-btn {
		margin: 0 0;
		background: none;
		border: none;
		font-size: 24px;
		cursor: pointer;
		color: #999;
		transition: color 0.3s;
		line-height: 1;
		padding: 0;
	}

	.close-btn::after {
		display: none;
	}

	.close-btn:hover {
		color: #BD3124;
	}

	.dialog-body {
		padding: 20px 25px;
		max-height: 70vh;
		overflow-y: auto;
		font-size: 15px;
		color: #333;
	}

	.form-group {
		display: flex;
		flex-direction: column;
		margin-bottom: 18px;
	}

	.form-group label,
	fieldset legend {
		font-weight: 600;
		margin-bottom: 8px;
		color: #555;
		user-select: none;
	}

	.required {
		color: #BD3124;
		margin-left: 3px;
	}

	.input-field {
		padding: 10px 14px;
		border-radius: 8px;
		border: 1.8px solid #ccc;
		font-size: 15px;
		transition: border-color 0.3s;
	}

	.input-field:focus {
		outline: none;
		border-color: #BD3124;
		box-shadow: 0 0 8px rgba(189, 49, 36, 0.3);
	}

	textarea {
		width: 280px;
		max-height: 60px;
		overflow: scroll;
	}

	.fault-types {
		display: flex;
		flex-wrap: wrap;
		gap: 12px;
	}

	.fault-types label {
		font-size: 14px;
		cursor: pointer;
		user-select: none;
		padding-left: 6px;
		position: relative;
	}

	.fault-types input[type="checkbox"] {
		width: 18px;
		height: 18px;
		margin-right: 6px;
		vertical-align: middle;
		cursor: pointer;
		accent-color: #BD3124;
	}

	.dialog-footer {
		display: flex;
		justify-content: space-between;
		padding: 20px 25px;
	}

	.cancel-btn,
	.submit-btn {
		flex: 1;
		margin: 0 5px;
		padding: 12px 0;
		border-radius: 25px;
		font-size: 16px;
		cursor: pointer;
		border: none;
		user-select: none;
		transition: background-color 0.3s ease;
	}

	.cancel-btn {
		color: #333;
		border: 0.5px solid #333;
		background-color: #FFF;
	}

	.submit-btn {
		background-color: #BD3124;
		color: #fff;
		font-weight: 700;
		box-shadow: 0 4px 12px rgba(189, 49, 36, 0.6);
	}

	.submit-btn:hover {
		background-color: #a42820;
		box-shadow: 0 6px 16px rgba(164, 40, 32, 0.8);
	}
</style>